﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Reflection;
using System.ComponentModel.DataAnnotations;

namespace Sparkle.UI
{
    public class MetaBinding : Binding
    {
        public MetaBinding()
            : base()
        {
        }

        public MetaBinding(string path)
            : base(path)
        {
        }

        public MetaBinding(string path, Metadata metadata)
            : base(path)
        {
            base.Converter = metadata;
        }

        public new object Source 
        {
            get { return base.Source ; }
            set 
            { 
                base.Source= value ; 
                #if ! SILVERLIGHT
                SetValidationRules();
                #endif
            }
        }
#if ! SILVERLIGHT
        protected void SetValidationRules()
        {
            if (base.Source != null && this.Path != null && !string.IsNullOrEmpty(this.Path.Path))
            {
                PropertyInfo property = base.Source.GetType().GetProperty(this.Path.Path);
                if (property != null)
                {
                    IEnumerable<object> attributes = property.GetCustomAttributes(true).Where(o => o is ValidationAttribute);
                    foreach (ValidationAttribute validationRule in attributes)
                        ValidationRules.Add(new SparkleValidationRule(validationRule));
                }
            }
        }
#endif

    }
}
